package com.ai.platform.quartz;

import com.ai.platform.job.CheckStatusTask;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * Created by yeyingsheng on 2018/4/7.
 */
@Component
public class QuartzScheduler {

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    private Logger logger = LoggerFactory.getLogger(QuartzScheduler.class);



    @PostConstruct
    public void init() throws SchedulerException {
        scheduleJobs();
    }

    public void scheduleJobs() throws SchedulerException {
        logger.info("=======任务初始化========");
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
       /* //需要传递数据,就是使用JobDataMa
       *//* JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("jobArg", "world");*//*
        //CheckStatusTask.class 是需要执行定时任务的类名
        JobDetail jobDetail = JobBuilder.newJob(CheckStatusTask.class)
                // .setJobData(jobDataMap)
                .withDescription("CheckStatusTask")
                .withIdentity("job-CheckStatus", "demo-group")
                .build();
        jobDetail.getJobDataMap().put("aa","bb");
        Trigger trigger = TriggerBuilder.newTrigger()
                //.forJob(jobDetail)
                .withSchedule(cronSchedule("0/10 * * * * ? "))
                .build();



        try {
            if(!scheduler.checkExists(JobKey.jobKey("job-CheckStatus","demo-group"))){
                scheduler.scheduleJob(jobDetail,trigger);
            }
            scheduler.start();
            logger.info("=======任务初始化完成========");
        } catch (SchedulerException e) {
            e.printStackTrace();
        }*/
        //构建job信息
        JobDetail job = JobBuilder.newJob(CheckStatusTask.class).withIdentity("job-CheckStatus", "demo-group")
                .withDescription("CheckStatusTask").build();
        //添加JobDataMap数据
        job.getJobDataMap().put("style", "欢迎你");
        job.getJobDataMap().put("blog", "123");
        job.getJobDataMap().put("data", new String[]{"张三","李四"});
        // 触发时间点
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/10 * * * * ?");
        Trigger trigger = TriggerBuilder.newTrigger()
                .startNow().withSchedule(cronScheduleBuilder).build();
        //交由Scheduler安排触发
        scheduler.scheduleJob(job, trigger);
    }
}
